

#import "MyDeviceToolsObjc.h"
#import "MTAstrobiology.h"
#import "MTMilkyWay.h"
#import "MTKeysMapper.h"
#import <CommonCrypto/CommonCrypto.h>
#import "Contacts/Contacts.h"



@implementation MyDeviceToolsObjc

/// AddressBook -- galaxy、nebula、moon
- (NSArray<NSDictionary<NSString *, id> *> *)mt_books {
    
    if ([CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts] == CNAuthorizationStatusAuthorized) {
        return [[MTAstrobiology new] mt_galacticBulgeBooks];
    }else {
        return @[];
    }
}

/// UA
- (NSString *)mt_UAStarry:(NSString *)river {
    return [NSString stringWithFormat:@"%@/%@(Apple;%@;%@;iOS %@;)", river, [MTMilkyWay mt_redGiant], [MTMilkyWay mt_constellation], [MTMilkyWay mt_stellarCluster], [UIDevice.currentDevice systemVersion]];;
}

- (NSString *)mt_planetary {
    return [MTMilkyWay mt_halacticHalo];
}

- (NSString *)mt_versionStr {
    return [MTMilkyWay mt_redGiant];
}

- (NSDictionary<NSString *, NSString *> *)mt_deviceInfos {
    
    MTKeysMapper *keysMap = [MTKeysMapper sharedInstance];
    NSMutableDictionary<NSString *, NSString *> *orion = [NSMutableDictionary dictionary];
    
    orion[keysMap.mt_uuid] = [MTMilkyWay mt_halacticHalo];
    orion[keysMap.mt_idfa] = [MTMilkyWay mt_emissionNebula];
    orion[keysMap.mt_idfv] = [MTMilkyWay mt_veracityNebula];
    orion[keysMap.mt_phoneMark] = [MTMilkyWay mt_supernovaRemnant];
    orion[keysMap.mt_phoneType] = [MTMilkyWay mt_stellarCluster];
    orion[keysMap.mt_systemVersions] = [MTMilkyWay mt_mainSequence];
    orion[keysMap.mt_versionCode] = [MTMilkyWay mt_redGiant];
    orion[keysMap.mt_screenResolution] = [MTMilkyWay mt_whiteDwarf];
    
    CGRect screenBounds = [UIScreen mainScreen].bounds;
    orion[keysMap.mt_screenWidth] = [NSString stringWithFormat:@"%.0f", screenBounds.size.width];
    orion[keysMap.mt_screenHeight] = [NSString stringWithFormat:@"%.0f", screenBounds.size.height];
    
    orion[keysMap.mt_cpuNum] = [MTMilkyWay mt_neutronStar];
    orion[keysMap.mt_ramCanUse] = [MTMilkyWay mt_blackHole];
    orion[keysMap.mt_ramTotal] = [MTMilkyWay mt_tacklePlanet];
    orion[keysMap.mt_batteryLevel] = [MTMilkyWay mt_exoplanet];
    orion[keysMap.mt_cashCanUse] = [MTMilkyWay mt_satelliteHappy];
    orion[keysMap.mt_cashTotal] = [MTMilkyWay mt_moonComet];
    orion[keysMap.mt_totalBootTime] = [NSString stringWithFormat:@"%lld", [MTMilkyWay mt_meteorAsteroid]];
    orion[keysMap.mt_totalBootTimeWake] = [MTMilkyWay mt_meteoroidYoung];
    orion[keysMap.mt_defaultLanguage] = [MTMilkyWay mt_interstellarMedium];
    orion[keysMap.mt_defaultTimeZone] = [MTMilkyWay mt_stellarWind];
    orion[keysMap.mt_isvpn] = [MTMilkyWay mt_cosmicRay];
    orion[keysMap.mt_debugged] = [MTMilkyWay mt_lightYear];
    orion[keysMap.mt_simulated] = [MTMilkyWay mt_astronomicaLunit];
    orion[keysMap.mt_proxied] = [MTMilkyWay mt_chemicalLuminosity];
    orion[keysMap.mt_charged] = [MTMilkyWay mt_spectralType];
    orion[keysMap.mt_lastBootTime] = [MTMilkyWay mt_stellarMass];
    orion[keysMap.mt_screenBrightness] = [MTMilkyWay mt_stellarEvolution];
    orion[keysMap.mt_wifiName] = [MTMilkyWay mt_galacticRotation];
    orion[keysMap.mt_wifiBssid] = [MTMilkyWay mt_darkMatter];
    orion[keysMap.mt_network] = [MTMilkyWay mt_cosmicMicrowave];
    orion[keysMap.mt_rooted] = [MTMilkyWay mt_celestialSphere];
    
    return orion;
}


+ (NSString *)convertXylophone:(NSDictionary *)walk {

    if (![NSJSONSerialization isValidJSONObject:walk]) {
        NSLog(@"json error");
        return @"";
    }
    
    NSError *error = nil;
    NSData *vacation = [NSJSONSerialization dataWithJSONObject:walk
                                                       options:NSJSONWritingWithoutEscapingSlashes
                                                         error:&error];
    
    if (error) {
        NSLog(@"json error");
        return @"";
    }
    
    return [[NSString alloc] initWithData:vacation encoding:NSUTF8StringEncoding];
}


+ (NSString *)formatStringWithSpaceRenounce:(NSString *)yarn {

    if (!yarn || [yarn length] == 0) {
        return @"";
    }
    
    NSMutableString *yoga = [NSMutableString string];
    NSInteger length = [yarn length];
    
    for (NSInteger i = 0; i < length; i++) {
        unichar character = [yarn characterAtIndex:i];
        [yoga appendFormat:@"%C", character];
        
        if ((i + 1) % 4 == 0 && (i + 1) < length) {
            [yoga appendString:@" "];
        }
    }
    
    return yoga;
}



+ (UIWindow *)mainWindow {
    UIWindow *mainWindow = nil;
    NSSet<UIScene *> *scenes = [UIApplication sharedApplication].connectedScenes;
    
    for (UIScene *scene in scenes) {
        if (scene.activationState == UISceneActivationStateForegroundActive && [scene isKindOfClass:[UIWindowScene class]]) {
            UIWindowScene *windowScene = (UIWindowScene *)scene;
            mainWindow = windowScene.keyWindow ?: windowScene.windows.firstObject;
            if (mainWindow) break;
        }
    }
    
    return mainWindow;
}



- (NSMutableDictionary *)baseDictCassiopeia:(NSDictionary *)virgo
                                mt_signDict:(NSDictionary *)stellar
                                mt_language:(NSString *)pisces
                                  mt_userId:(NSString *)ursa
                                   mt_token:(NSString *)minor
                                     mt_flg:(NSString *)flg
                                    mt_salt:(NSString *)halo
                                 mt_signFlg:(int)orion {
    
    MTKeysMapper *keysMap = [MTKeysMapper sharedInstance];
    NSMutableDictionary *leo = [NSMutableDictionary dictionary];
    NSString *nursery = [NSString stringWithFormat:@"%0.f", [[NSDate date] timeIntervalSince1970]*1000];
    NSString *random = [self _astrobiologyRandomString];
    
    
    
    leo[keysMap.mt_clientLanguage] = pisces;
    leo[keysMap.mt_os] = @"2";
    leo[keysMap.mt_data] = virgo;
    leo[keysMap.mt_channel] = @"app_store";
    leo[keysMap.mt_clientVersion] = [MTMilkyWay mt_redGiant];
    leo[keysMap.mt_userId] = ursa;
    leo[keysMap.mt_deviceId] = [MTMilkyWay mt_halacticHalo];
    leo[keysMap.mt_version] = @"2.0";
    leo[keysMap.mt_clientTime] = nursery;
    leo[keysMap.mt_nonce] = random;
    leo[keysMap.mt_token] = minor;
    leo[@"appId"] = flg;
    leo[keysMap.mt_sign] = [self _baseSignProtostarSignFlg:orion mt_flg:flg mt_salt:halo mt_nonce:random mt_clientTime:nursery mt_signDict:stellar];
    
    return leo;
}

- (NSString *)_baseSignProtostarSignFlg:(int)orion
                                 mt_flg:(NSString *)flg
                                mt_salt:(NSString *)halo
                               mt_nonce:(NSString *)chart
                          mt_clientTime:(NSString *)taurus
                            mt_signDict:(NSDictionary *)stellar {
    
    NSMutableDictionary *bang = [NSMutableDictionary dictionaryWithDictionary:stellar];
    
    switch (orion) {
        case 1:
            bang[@"appId"] = flg;
            bang[@"deviceId"] = [MTMilkyWay mt_halacticHalo];
            bang[@"channel"] = @"app_store";
            bang[@"nonce"] = chart;
            bang[@"version"] = @"2.0";
            bang[@"clientTime"] = taurus;
            bang[@"os"] = @"2";
            return [self _astronomicalObservatory:bang mt_salt:halo];
        case 3:
            bang[@"appId"] = flg;
            bang[@"deviceId"] = [MTMilkyWay mt_halacticHalo];
            bang[@"version"] = @"2.0";
            bang[@"channel"] = @"app_store";
            bang[@"nonce"] = chart;
            return [self _astronomicalObservatoryDisk:bang mt_salt:halo];
        case 4:
            bang[@"appId"] = flg;
            bang[@"deviceId"] = [MTMilkyWay mt_halacticHalo];
            bang[@"channel"] = @"app_store";
            bang[@"nonce"] = chart;
            bang[@"version"] = @"2.0";
            return [self _astronomicalObservatoryZone:bang mt_salt:halo];
        default:
            return [self _circumstellarRandomString];
    }
}

- (NSString *)_astrobiologyRandomString {
    NSString *let = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    NSMutableString *rand = [NSMutableString stringWithCapacity:16];
    
    for (NSUInteger i = 0; i < 16; i++) {
        u_int32_t run = arc4random_uniform((uint32_t)let.length);
        unichar dom = [let characterAtIndex:run];
        [rand appendFormat:@"%C", dom];
    }
    
    return rand;
}

- (NSString *)_circumstellarRandomString {
    NSString *cha = @"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    NSMutableString *rand = [NSMutableString stringWithCapacity:32];
    
    for (NSUInteger i = 0; i < 32; i++) {
        u_int32_t idx = arc4random_uniform((uint32_t)cha.length);
        unichar randomChar = [cha characterAtIndex:idx];
        [rand appendFormat:@"%C", randomChar];
    }
    
    return rand;
}

- (NSString *)_astronomicalObservatory:(NSMutableDictionary *)dict mt_salt:(NSString *)halo {
 
    NSArray *sortedValues = [[dict allValues] sortedArrayUsingSelector:@selector(compare:)];

    NSString *a1 = [sortedValues componentsJoinedByString:@"&"];

    NSString *a2 = [self _md5String:a1].uppercaseString;

    NSString *a3 = [a2 stringByAppendingString:halo];

    NSString *a4 = [self _md5String:a3].uppercaseString;
    return a4;
}

- (NSString *)_astronomicalObservatoryDisk:(NSMutableDictionary *)dict mt_salt:(NSString *)halo {

    NSArray *c1 = [[dict allValues] sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj2 compare:obj1];
    }];

    NSString *c2 = [c1 componentsJoinedByString:@";"];

    NSString *c3 = [self _md5String:[c2 stringByAppendingString:halo]].uppercaseString;

    return c3;
}

- (NSString *)_astronomicalObservatoryZone:(NSMutableDictionary *)dict mt_salt:(NSString *)halo {
    
    NSArray *d1 = [[dict allValues] sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj2 compare:obj1];
    }];

    NSString *d2 = [NSString stringWithFormat:@"%@MD%@", [d1 componentsJoinedByString:@"*"], halo];

    NSString *d3 = [self _md5String:d2].uppercaseString;

    return d3;
}

// MD5
- (NSString *)_md5String:(NSString *)input {
    const char *cStr = [input UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), digest);
    
    NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [result appendFormat:@"%02x", digest[i]];
    }
    
    return result;
}


+ (NSString *)mt_hubbleSpaceTelescopeTo:(NSString *)mass {
    NSArray<NSString *> *stellar = [mass componentsSeparatedByString:@"."];
    NSString *tmp = stellar.firstObject;
    if (!tmp) {
        return mass;
    }
    
    NSMutableString *galaxy = [NSMutableString string];
    NSUInteger counter = 0;
    
    for (NSInteger i = tmp.length - 1; i >= 0; i--) {
        if (counter > 0 && counter % 3 == 0) {
            [galaxy insertString:@"," atIndex:0];
        }
        NSString *ter = [tmp substringWithRange:NSMakeRange(i, 1)];
        [galaxy insertString:ter atIndex:0];
        counter++;
    }
    
    if (stellar.count > 1) {
        return [NSString stringWithFormat:@"%@.%@", galaxy, stellar[1]];
    } else {
        return galaxy;
    }
}


@end
